const express = require('express');
const app = express();
const PORT = 3000;

/* ===== 内置中间件 ===== */
app.use(express.json());            // 解析 JSON
app.use(express.urlencoded({ extended: true })); // 解析表单

/* ===== 假数据 ===== */
let counter = 0;
const todos = [
  { id: 1, title: '学习 Express', done: false },
  { id: 2, title: '写 zjr.js', done: true }
];
let nextId = 3;

/* ===== 路由 ===== */

// 根路径提示
app.get('/', (req, res) => {
  res.send(`
Express 版 zjr.js 已启动！`)
});

// 心跳
app.get('/ping', (_, res) => res.json({ msg: 'pong' }));

// 计数器
app.get('/counter', (_, res) => res.json({ counter }));
app.post('/counter', (_, res) => res.json({ counter: ++counter }));

// 待办 CRUD
app.get('/todos', (_, res) => res.json(todos));

app.get('/todos/:id', (req, res) => {
  const item = todos.find(t => t.id === Number(req.params.id));
  if (!item) return res.status(404).json({ error: 'Not Found' });
  res.json(item);
});

app.post('/todos', (req, res) => {
  const { title } = req.body;
  if (!title) return res.status(400).json({ error: 'title 必填' });
  const todo = { id: nextId++, title, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});

app.put('/todos/:id', (req, res) => {
  const item = todos.find(t => t.id === Number(req.params.id));
  if (!item) return res.status(404).json({ error: 'Not Found' });
  item.done = !item.done;
  res.json(item);
});

app.delete('/todos/:id', (req, res) => {
  const idx = todos.findIndex(t => t.id === Number(req.params.id));
  if (idx === -1) return res.status(404).json({ error: 'Not Found' });
  const [removed] = todos.splice(idx, 1);
  res.json(removed);
});

/* ===== 启动 ===== */
app.listen(PORT, () => {
  console.log(`zjr.js (Express) 已启动 → http://localhost:${PORT}`);
});

// | 方法     | 地址                               | 预期返回 JSON（已格式化）                                                                        | 说明           |
// | ------ | -------------------------------- | -------------------------------------------------------------------------------------- | ------------ |
// | GET    | `/ping`                          | `{"msg":"pong"}`                                                                       | 心跳           |
// | GET    | `/counter`                       | `{"counter":0}`                                                                        | 初始值          |
// | POST   | `/counter`                       | `{"counter":1}`                                                                        | 每 POST 一次 +1 |
// | GET    | `/todos`                         | `[{"id":1,"title":"学习 Express","done":false},{"id":2,"title":"写 zjr.js","done":true}]` | 初始两条假数据      |
// | GET    | `/todos/1`                       | `{"id":1,"title":"学习 Express","done":false}`                                           | 单条存在         |
// | GET    | `/todos/99`                      | `{"error":"Not Found"}`                                                                | 不存在 → 404    |
// | POST   | `/todos`<br>请求体 `{"title":"复习"}` | `{"id":3,"title":"复习","done":false}`                                                   | 201 创建成功     |
// | POST   | `/todos`<br>无 title              | `{"error":"title 必填"}`                                                                 | 400 参数错误     |
// | PUT    | `/todos/1`                       | `{"id":1,"title":"学习 Express","done":true}`                                            | 切换完成状态       |
// | PUT    | `/todos/99`                      | `{"error":"Not Found"}`                                                                | 404          |
// | DELETE | `/todos/2`                       | `{"id":2,"title":"写 zjr.js","done":true}`                                              | 删除并返回被删项     |
// | DELETE | `/todos/99`                      | `{"error":"Not Found"}`                                                                | 404          |
